<template>
	<div class="articleManage">
		<div class="public-search-box">
			<el-form inline
					 ref="searchRef"
					 :model="searchData">
				<el-form-item>
					<el-input v-model="searchData.title"
							  size="small"
							  clearable
							  placeholder="标题"
							  @input="pageChange(1)">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-search"
							   v-if="hasPerm('article:list')"
							   @click="pageChange(1)">查询
					</el-button>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-plus"
							   v-if="hasPerm('article:add')"
							   @click="addOrUpdate('add')">新增
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="public-table"
			 v-loading="loading"
			 element-loading-text="拼命加载中...">
			<el-table :data="list"
					  height="calc(100vh - 114px - 30px - 61px - 72px - 30px)"
					  style="width: 100%;">
				<el-table-column prop="orderNumber"
								 label="序号"
								 align="center"></el-table-column>
				<el-table-column prop="title"
								 label="标题"
								 align="center"></el-table-column>
				<el-table-column prop="cname"
								 label="栏目名称"
								 align="center"></el-table-column>
				<!--<el-table-column prop="author"-->
				<!--				 label="作者"-->
				<!--				 align="center"></el-table-column>-->
				<el-table-column prop="image"
								 label="缩略图"
								 align="center">
					<template slot-scope="scope">
						<img :src="getImg(scope.row)"
							 alt=""
							 style="width: 100px;height: 100px;">
					</template>
				</el-table-column>
				<el-table-column prop="intro"
								 label="简介"
								 align="center"></el-table-column>
				<el-table-column prop="keyword"
								 label="关键词"
								 align="center"></el-table-column>
				<el-table-column prop="content"
								 label="内容"
								 align="center">
					<template slot-scope="scope">
						<span>{{ decodeURI(scope.row.content).replace(/&lt;\/?.+?>/g, '').substr(0, 50) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="created_time"
								 label="创建/更新时间"
								 align="center">
					<template slot-scope='scope'>
						<span>{{ scope.row.created_time | dateTime }}</span>
						<br>
						<br>
						<span>{{ scope.row.updated_time | dateTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作"
								 align="center">
					<template slot-scope="scope">
						<el-button type="primary"
								   size="small"
								   v-if="hasPerm('article:edit')"
								   @click="addOrUpdate('update', scope.row)">修改
						</el-button>
						<el-button type="danger"
								   size="small"
								   v-if="hasPerm('article:delete')"
								   @click="del(scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination :total="total"
					:page="searchData.currentPage"
					:pageSize="searchData.pageSize"
					@pageChange="pageChange">
		</pagination>
		<el-dialog :title="saveData.id === '' ? '新增' : '修改'"
				   width="800px"
				   custom-class="public-dialog"
				   :close-on-click-modal="false"
				   :visible.sync="addOrUpdateVisible"
				   :before-close="close">
			<el-form ref="addOrUpdateRef"
					 :model="saveData"
					 :rules="addOrUpdateRules"
					 label-width="70px">
				<el-form-item label="标题:"
							  prop="title">
					<el-input v-model="saveData.title"
							  size="small"></el-input>
				</el-form-item>
				<el-form-item label="缩略图:"
							  prop="image">
					<uploadImg ref="uploadImg"
							   :fileList=fileList
							   @uploadImgSuccess="uploadImgSuccess"></uploadImg>
				</el-form-item>
				<el-form-item label="栏目:"
							  prop="cid">
					<el-select v-model="culumnObj"
							   size="small"
							   @change="culumnChange"
							   value-key="id"
							   style="width: 100%;">
						<el-option v-for="(item, index) in columnList"
								   :key="index"
								   :label="item.name"
								   :value="item">
						</el-option>
					</el-select>
				</el-form-item>
				<!--<el-form-item label="作者:"-->
				<!--			  prop="author">-->
				<!--	<el-input v-model="saveData.author"-->
				<!--			  size="small"></el-input>-->
				<!--</el-form-item>-->
				<el-form-item label="简介:"
							  prop="intro">
					<el-input v-model="saveData.intro"
							  size="small"></el-input>
				</el-form-item>
				<el-form-item label="关键词:"
							  prop="keyword">
					<el-input v-model="saveData.keyword"
							  size="small"></el-input>
				</el-form-item>
				<el-form-item label="内容:"
							  prop="content">
					<wangeditor @edit="edit"
								ref="wangeditorRef"></wangeditor>
				</el-form-item>
			</el-form>
			<span slot="footer">
                <el-button size="small"
						   @click="close">取消</el-button>
                <el-button type="primary"
						   size="small"
						   @click="submit">保存</el-button>
            </span>
		</el-dialog>
	</div>
</template>

<script>
import uploadImg from '@/components/uploadImg/uploadImg'
import pagination from '@/components/pagination/pagination'
import wangeditor from '@/components/wangeditor/wangeditor'
import { articleApi, columnApi, tabApi } from '@/api'
import { numSort } from '@/utils'

export default {
	name: 'admin',
	data () {
		return {
			fileList: [],
			dialogImageUrl: '',
			dialogVisible: false,
			searchData: {
				title: '',
				sort: 'id',
				order: 'ASC',
				currentPage: 1,
				pageSize: 10
			},
			loading: true,
			total: 0,
			list: [],
			culumnObj: {},
			columnList: [],
			addOrUpdateVisible: false,
			saveData: {
				id: '',
				title: '',
				cid: '',
				cname: '',
				image: '',
				author: '',
				intro: '',
				keyword: '',
				content: ''
			},
			addOrUpdateRules: {
				title: [
					{ required: true, message: '请输入标题', trigger: 'blur' }
				],
				cid: [
					{
						required: true,
						message: '请选择栏目',
						trigger: 'change'
					}
				],
				// image: [
				// 	{
				// 		required: true,
				// 		message: '请上传图片',
				// 		trigger: 'change'
				// 	}
				// ],
				// author: [
				// 	{ required: true, message: '请输入作者', trigger: 'blur' }
				// ],
				// intro: [
				// 	{ required: true, message: '请输入简介', trigger: 'blur' }
				// ],
				// keyword: [
				// 	{
				// 		required: true,
				// 		message: '请输入关键词',
				// 		trigger: 'blur'
				// 	}
				// ],
				content: [
					{ required: true, message: '请输入内容', trigger: 'blur' }
				]
			},
			catchData: {
				name: '1'
			}
		}
	},
	mounted () {
		this.getList()
	},
	methods: {
		// 获取栏目列表
		async getColumnList () {
			const { err, data } = await columnApi.getList()
			if (err) {
				return false
			}
			this.columnList = data
		},
		// 获取列表
		async getList () {
			this.loading = true
			let params = Object.assign({}, this.searchData)
			const { err, data } = await articleApi.getPage(params)
			if (err) {
				return false
			}
			if (data.list.length === 0 && params.currentPage !== 1) {
				// 删除后判断当前页面是否无数据 如果有数据则正常处理数据，如不正常数据为空时。则重新获取有数据的页面条件
				// 删除后当前页面无数据时，则重新计算有数据的页面重新获取数据
				let current = Math.ceil(data.totalCount / params.pageSize)
				this.pageChange(current)
			} else {
				data.list.forEach((item, index) => {
					item['orderNumber'] = numSort(
						index,
						params.currentPage,
						params.pageSize
					)
				})
				this.list = data.list
				this.total = data.totalCount
				setTimeout(() => {
					this.loading = false
				}, 100)
			}
		},
		addOrUpdate (val, item) {
			this.addOrUpdateVisible = true
			this.getColumnList()
			if (val === 'update') {
				this.detDetail(item)
			}
		},
		culumnChange (item) {
			this.saveData.cid = item.id
			this.saveData.cname = item.name
		},
		edit (val) {
			this.saveData.content = val
		},
		// 提交
		submit () {
			let api = null
			let message = ''
			this.$refs.addOrUpdateRef.validate(async (valid) => {
				if (valid) {
					let params = Object.assign({}, this.saveData)
					let keyArr = params.keyword.split('、')
					this.addTab(keyArr)
					if (params.id === '') {
						api = articleApi.addData
						message = '添加成功'
					} else {
						api = articleApi.updateData
						message = '更新成功'
					}
					const { err, data } = await api(params)
					if (err) {
						return false
					}
					this.$message({
						message: message,
						type: 'success'
					})
					this.close()
					this.getList()
				}
			})
		},
		async addTab (arr) {
			let a = []
			arr.forEach((item) => {
				let obj = {
					name: item
				}
				a.push(obj)
			})
			const { err, data } = await tabApi.addData(a)
			if (err) {
				return false
			}
		},
		// 获取详情
		async detDetail (item) {
			const { err, data } = await articleApi.detailData(item.id)
			if (err) {
				return false
			}
			this.saveData.id = data.id
			this.saveData.title = data.title
			this.culumnObj = {
				id: data.cid,
				name: data.cname
			}
			this.saveData.cid = data.cid
			this.saveData.image = data.image
			this.saveData.author = data.author
			this.saveData.intro = data.intro
			this.saveData.keyword = data.keyword
			this.saveData.content = data.content
			this.$refs.wangeditorRef.setContent(data.content, 1)
			this.fileList = [
				{
					url: 'api' + data.image
				}
			]
		},
		// 删除
		del (item) {
			this.$confirm('确定删除当前数据吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const { err, data } = await articleApi.delData(item)
				if (err) {
					return false
				}
				this.$message({
					message: '删除成功',
					type: 'success'
				})
				this.getList()
			}).catch(() => {})
		},
		// 图片上传成功
		uploadImgSuccess (data) {
			this.saveData.image = data.url
		},
		// 分页
		pageChange (val, size) {
			if (size) {
				this.searchData.pageSize = size
			}
			this.searchData.currentPage = val
			this.getList()
		},
		// 关闭
		close () {
			this.addOrUpdateVisible = false
			this.saveData.id = ''
			this.saveData.image = ''
			this.$refs.addOrUpdateRef.resetFields()
			this.culumnObj = null
			this.$refs.wangeditorRef.setContent()
			this.fileList = []
		}
	},
	computed: {
		getImg () {
			return function (item) {
				return process.env.VUE_APP_BASE_API + item.image
			}
		}
	},
	components: {
		uploadImg,
		pagination,
		wangeditor
	}
}
</script>

<style scoped lang="less">
.articleManage {
	width: 100%;
}

.avatar-uploader {
	/deep/ .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
